package com.qfedu.repo.dao.impl;

import com.qfedu.repo.bean.Product;
import com.qfedu.repo.dao.ProductDao;
import com.qfedu.repo.db.DBUtils;
import com.qfedu.repo.db.PstCallback;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ProductDaoImpl implements ProductDao {

    @Override
    public List<Product> getAllList() {
        //1、准备sql
        String sql = "select id,pno,pname,paddr,pdate,enterdate,pnumber from products";
        //2、调用jdbc攻击查询方法
        ResultSet resultSet = DBUtils.query(sql, null);
        //3、处理结果
        List<Product> list = new ArrayList<>();
        try {
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String pno = resultSet.getString("pno");
                String pname = resultSet.getString("pname");
                String paddr = resultSet.getString("paddr");
                String pdate = resultSet.getString("pdate");
                String enterdate = resultSet.getString("enterdate");
                int pnumber = resultSet.getInt("pnumber");
                Product product = new Product(id, pno, pname, paddr, pdate, enterdate, pnumber);
                list.add(product);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            //4、关闭连接
            if (resultSet != null) {
                try {
                    resultSet.close();
                    DBUtils.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        return list;
    }

    @Override
    public int addProduct(Product product) {
        //目标：dao实现层；操作数据库
        //1.准备sql
        String sql = "insert into products(pno,pname,paddr,pdate,enterdate,pnumber) values(?,?,?,?,?,?)";
        return DBUtils.executeUpdate(sql, new PstCallback() {
            @Override
            public void pstSetValue(PreparedStatement pst) {
                try {
                    pst.setString(1, product.getPno());
                    pst.setString(2, product.getPname());
                    pst.setString(3, product.getPaddr());
                    pst.setString(4, product.getPdate());
                    pst.setString(5, product.getEnterDate());
                    pst.setInt(6, product.getpNumber());

                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }
}
